﻿/// <summary>
/// DAL.Net Framework
/// Copyright (C) 2008 Fuji Service System Project Team
/// 编写人：冯静
/// 编写日期：2008-12-10
/// 功能描述：考勤管理视图层
/// </summary>
using System;
using System.Collections;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using CommonComponent;
using Iesi.Collections;
using MOD.PersonnelOffice.WorkingReport;
using BLL;
using CommonComponent.Common;
using DAL;
using BLL.Dms;
using PermissionBase.Core.Domain;
using PermissionBase.Core.Service;
/// <summary>
/// EOaWorkingReg 的摘要说明
/// </summary>
public class EOaWorkingReport
{

    BOaWorkingReport OaWork = new BOaWorkingReport();
    BDmsDataDict dict = new BDmsDataDict();//实例化数据字典业务层
    public EOaWorkingReport()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
  
    #region 工作日志
    /// <summary>
    /// 工作日志 初始化页面
    /// <param name="reg">考勤实体类</param>
    /// <returns>1表示成功创建,0表示创建失败</returns>
    public OaWorkingReg Initialization(string date, string userID)
    {
        try
        {

            OaWorkingReg result = OaWork.OaWorkingRegByDateAndUserID(date, userID);
            return result;
        }
        catch (Exception ex)
        {
            CommonComponent.WebPage.JScript.JsAlert(ex.Message);
            return null;
        }

    }
    /// <summary>
    /// 工作日志 上班登记
    /// <param name="reg">考勤实体类</param>
    /// <returns>1表示成功创建,0表示创建失败</returns>
    public int CheckIn(string memo)
    {

        //获取规定的上班时间
        string RegisterOnTimeByLaw = ConfigurationSettings.AppSettings["RegisterOnTimeByLaw"];

        //实例化考勤实体
        OaWorkingReg reg = new OaWorkingReg();


        //向实体类中赋值
        string userID = SessionUtil.GetStaffSession().LoginId;
        reg.Comp_code = "00";
        reg.Emp_code = userID;
        reg.Reg_on_datetime = System.DateTime.Now;
        reg.Reg_off_datetime = CommonComponent.Common.TimeConvert.StringToDateTime("1900-01-01", "yyyy-MM-dd");
        reg.Today_knowledge = "";
        reg.Tomorrow_plan = "";
        reg.Working_memo = memo;
        reg.Working_time = 0.0f;

        //上班登记时间
        string CheckInDate = reg.Reg_on_datetime.TimeOfDay.ToString().Substring(0, 5);


        //用上班登记时间与规定的上班时间做比较,
        //如果上班登记时间大于规定时间,状态(Reg_type)为迟到,则否为正常.
        //Reg_type 01-正常  02-迟到 03-早退 04-迟到早退 05-旷工

        if (CheckInDate.CompareTo(RegisterOnTimeByLaw) > 0)
        {
            reg.Reg_type =DictEnums.formatDictCode((int) DictEnums.WorkingRegister.Later);//迟到
        }
        else
        {
            reg.Reg_type = DictEnums.formatDictCode((int)DictEnums.WorkingRegister.EnRegister);//正常登记
        }

        int result = 0;

        try
        {
            result = OaWork.CreateOaWorkingReg(reg);
        }
        catch (Exception ex)
        {
            CommonComponent.WebPage.JScript.JsAlert(ex.Message);
        }
        return result;
    }
    /// <summary>
    /// 工作日志 下班登记或保存整个日志
    /// <param name="reg">考勤实体类</param>
    /// <returns>1表示成功创建,0表示创建失败</returns>
    public int CheckOutOrSaveButton(string updateFields, SqlParameter[] parms)
    {
        int result = 0;

        try
        {
            result = OaWork.UpdateOaWorkingReg(updateFields, parms);
        }
        catch (Exception ex)
        {
            CommonComponent.WebPage.JScript.JsAlert(ex.Message);
        }
        return result;
    }
    /// <summary>
    /// 工作日志 添加日志
    /// <param name="reg">工作日志实体类</param>
    /// <returns>1表示成功创建,0表示创建失败</returns>
    public int AddWorkingReport(OaWorkingReport report)
    {


        int result = 0;

        try
        {
            result = OaWork.CreateOaWorkingReport(report);
        }
        catch (Exception ex)
        {
            CommonComponent.WebPage.JScript.JsAlert(ex.Message);
        }
        return result;
    }
    /// <summary>
    /// 工作日志 删除工作日志
    /// </summary>
    /// <param name="user">工作日志实体对象</param>
    /// <returns>影响数据库记录行数</returns>
    public int DeleteOaWorkingReport(string pkid)
    {
        int result = 0;

        try
        {
            result = OaWork.DeleteOaWorkingReport(pkid);
        }
        catch (Exception ex)
        {
            CommonComponent.WebPage.JScript.JsAlert(ex.Message);
        }
        return result;
    }
    /// <summary>
    /// 工作日志 绑定工作类型列表
    /// </summary>
    /// <param name="DropDownWorkType"></param>
    public void BindWorkingType(ref DropDownList DropDownWorkType)
    {

        DataSet ds1 = dict.GetDmsDataDictInfoByDictSort(Constants.SESSION_WORKING_TYPE, Tables.TBL_ASS_DATA_DICT);

        DropDownWorkType.DataSource = ds1.Tables[0].DefaultView;
        DropDownWorkType.DataValueField = ds1.Tables[0].Columns["dict_code"].ColumnName;
        DropDownWorkType.DataTextField = ds1.Tables[0].Columns["dict_name"].ColumnName;
        DropDownWorkType.DataBind();
    
    }
    /// <summary>
    /// 工作日志 绑定成本项列表 
    /// </summary>
    /// <param name="DropDownWorkCost"></param>
    public void BindWorkingCost(ref DropDownList DropDownWorkCost)
    {
      
        DataSet ds2 = dict.GetDmsDataDictInfoByDictSort(Constants.SESSION_WORKING_COST, Tables.TBL_ASS_DATA_DICT);
        DropDownWorkCost.DataSource = ds2.Tables[0].DefaultView;
        DropDownWorkCost.DataValueField = ds2.Tables[0].Columns["dict_code"].ColumnName;
        DropDownWorkCost.DataTextField = ds2.Tables[0].Columns["dict_name"].ColumnName;
        DropDownWorkCost.DataBind();    
    }
    /// <summary>
    /// 工作日志 绑定已经填写的工作日志
    /// </summary>
    /// <param name="userID"></param>
    /// <param name="head_id"></param>
    /// <param name="GridViewWorkingReport"></param>
    public void BindOldWorkingReport(ref string userID,string head_id,GridView GridViewWorkingReport ) {

        string strSQL = "select * from " + Tables.VIEW_OA_WORKING_REPORT + " where emp_code='" + userID + "' and head_id='" + head_id + "' ORDER BY start_time";
        DataSet dr = OaWork.GetDataSetOaWorkingReportList(strSQL, Tables.TBL_OA_WORKING_REPORT);
        GridViewWorkingReport.DataSource = dr;
        GridViewWorkingReport.DataKeyNames = new string[] { "pk_id" };//主键
        GridViewWorkingReport.DataBind();
        dr.Dispose();
      
    }
    #endregion

    #region 考勤查询
    /// <summary>
    /// 考勤查询 初始方法
    /// </summary>
    /// <param name="dataList"></param>
    public void SearchWorkingReportPageLoad(ref DataList dataList) {
        string strSQL = "select * from " + Tables.VIEW_OA_WORKING_REG;
        SqlDataReader dr1 = OaWork.GetOaWorkingRegList(strSQL);
        dataList.DataSource = dr1;
        dataList.DataBind();
        dr1.Close();

    }
    
    /// <summary>
    /// 考勤查询 查询方法
    /// </summary>
    /// <param name="sEmpCode"></param>
    /// <param name="sBeginDate"></param>
    /// <param name="sEndDate"></param>
    /// <param name="dataList"></param>
    public void SearchWorkingReprot(ref string sEmpCode, string sBeginDate, string sEndDate,DataList dataList)
    {

        Boolean needAnd = false;
        string strSQL = "select * from " + Tables.VIEW_OA_WORKING_REG + " where ";        

        //处理人员/组织机构选择框的查询条件拼接sql
        if (!sEmpCode.Equals(""))
        {
            if (needAnd)
            {
                strSQL = strSQL + " and " ;
            }
            //added maudyi 2009-04-13，添加了可以按照组织机构查询的功能
            if (sEmpCode.StartsWith(Constants.TREE_NODE_ID_ORG_PREFIX))
            {
                string organId = sEmpCode.Substring(Constants.TREE_NODE_ID_ORG_PREFIX.Length);
                ArrayList res = new ArrayList();
                Department currOrgan = CommonSrv.LoadObjectById(typeof(Department), organId) as Department;
                string[] organIds = this.LoadDepartmentIds(ref res,currOrgan);
                strSQL += "organ_code in(";
                for (int i = 0; i < organIds.Length;i++ )
                {
                    strSQL += " '" + organIds[i] + "' ";
                    if(i<organIds.Length-1)
                    {
                        strSQL += ",";
                    }
                }
                strSQL += ") ";
            } 
            else
            {
                strSQL = strSQL + " emp_code='" + sEmpCode + "'";
            }
            //end 2009-04-13
            needAnd = true;
            
        }

        //处理起始日期查询条件拼接sql
        if (!sBeginDate.Equals(""))
        {
            if (needAnd)
            {
                strSQL = strSQL + " and ";
            }
            
            strSQL = strSQL + " reg_date >='" + sBeginDate + "'";
            needAnd = true;
        }
        //处理终止日期查询条件拼接sql
        if (!sEndDate.Equals(""))
        {
            if (needAnd)
            {
                strSQL = strSQL + " and ";
            }
            
            strSQL = strSQL + " reg_date <='" + sEndDate + "'";
            needAnd = true;
        }

        #region 根据角色控制数据可见性
        //added 2009-04-14 maudyi
        //根据角色控制数据可见性
        StaffSession ss = SessionUtil.GetStaffSession();
        Staff s = StaffSrv.GetStaffByLoginIdAndSystemCode(ss.LoginId, ss.SystemCode);
        ISet roles = s.Roles;

        Role role_OfficeLead = CommonSrv.LoadObjectById(typeof(Role), "OfficeLead") as Role;
        Role role_AssManager = CommonSrv.LoadObjectById(typeof(Role), "AssManager") as Role;
        Role role_SecManager = CommonSrv.LoadObjectById(typeof(Role), "SecManager") as Role;
        Role role_Bmanager_1 = CommonSrv.LoadObjectById(typeof(Role), "Bmanager_1") as Role;
        Role role_Bmanager_2 = CommonSrv.LoadObjectById(typeof(Role), "Bmanager_2") as Role;
        Role role_VMinister = CommonSrv.LoadObjectById(typeof(Role), "VMinister") as Role;
        Role role_BMinister = CommonSrv.LoadObjectById(typeof(Role), "BMinister") as Role;
        Role role_VGManager = CommonSrv.LoadObjectById(typeof(Role), "VGManager") as Role;
        Role role_GManager = CommonSrv.LoadObjectById(typeof(Role), "GManager") as Role;

        //副总经理、总经理
        if (roles.Contains(role_VGManager) || roles.Contains(role_GManager))
        {
            //不用限制条件
        }
        //课长、部长、副部长
        else if (roles.Contains(role_AssManager) || roles.Contains(role_SecManager) || roles.Contains(role_Bmanager_1)
                || roles.Contains(role_Bmanager_2) || roles.Contains(role_VMinister) || roles.Contains(role_BMinister))
        {
            string organId = s.DefaultDepartment.Id;
            ArrayList res = new ArrayList();
            Department currOrgan = CommonSrv.LoadObjectById(typeof(Department), organId) as Department;
            string[] organIds = this.LoadDepartmentIds(ref res, currOrgan);

            if (needAnd)
            {
                strSQL = strSQL + " and ";
            }
            strSQL += "organ_code in(";
            for (int i = 0; i < organIds.Length; i++)
            {
                strSQL += " '" + organIds[i] + "' ";
                if (i < organIds.Length - 1)
                {
                    strSQL += ",";
                }
            }
            strSQL += ") ";
            
            needAnd = true;
        }
        //办事处主任
        else if (roles.Contains(role_OfficeLead))
        {
            string organId = s.DefaultDepartment.Id;
            if (needAnd)
            {
                strSQL = strSQL + " and ";
            }

            strSQL = strSQL + " organ_code='" + organId + "'";
            needAnd = true;
        }
        //其他情况，包括普通用户和管理员等，全是只能看自己的，就不用角色id单独控制了
        else
        {
            if (needAnd)
            {
                strSQL = strSQL + " and " ;
            }
            strSQL = strSQL + " emp_code='" + ss.LoginId + "'";
            needAnd = true;
        }

        #endregion

        //补充 1=1 来保证没有任何条件时候出现空where
        if (!needAnd)
        {
            strSQL += " 1=1 ";
        }


        strSQL = strSQL + " order by emp_code,reg_date DESC";
        Logger.debug(this, "根据角色控制工作查询数据可见性，sql语句是 " + strSQL);
        SqlDataReader dr = OaWork.GetOaWorkingRegList(strSQL);
        dataList.DataSource = dr;
        dataList.DataBind();
        dr.Close();  
    }

    private string[] LoadDepartmentIds(ref ArrayList res, Department currentDepartment)
    {
        IList subDepartments = null;
        if (currentDepartment != null)
        {
            res.Add(currentDepartment.Id);
            subDepartments = currentDepartment.SubDepartments;
        }
        else
            subDepartments = DepartmentSrv.GetAllTopDepartment(Constants.TOP_ORG_PARENT);

        foreach (Department d in subDepartments)
        {
            LoadDepartmentIds(ref res,d);
        }
        return (string[])res.ToArray(typeof(string));
    }
    
    /// <summary>
    /// 考勤查询 绑定工作日志明细
    /// </summary>
    /// <param name="oGridView"></param>
    public void BindWoringReportList(ref GridView oGridView,string head_id)
    {
        string sql = "select * from " + Tables.VIEW_OA_WORKING_REPORT + " Where head_id = '" + head_id + "' order by start_time ";
        SqlDataReader dr1 = OaWork.GetOaWorkingReportList(sql);
        oGridView.DataSource = dr1;
        oGridView.DataBind();
        dr1.Close();
    }
    #endregion
}
